package org.kev.transit.util;

import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Set;
import android.app.Activity;
import android.content.SharedPreferences;
import android.util.Log;

/**
 * static utility  methods.
 * @author kevin
 *
 */
public class TransitUtil {
	private static final String TAG = "TransitUtil";
	/**
 	 * dumps the values from a Object array with index to a string.  This is useful for debugging.
	 * @param list 
	 * @return dumped string
	 */
	public static String dump(Object[] list){
		StringBuffer buffer=new StringBuffer();
		if(list==null)
			return "[null]";
		for (int i=0;i<list.length;i++){
			Object o=list[i];
			if(o!=null){
				buffer.append("["+i+"]="+o.toString()+"," );
			}else{
				buffer.append("["+i+"]=[null],");
			}
		}
		return buffer.toString();	
	}
	/**
	 * dumps the values from a list with index to a string.  This is useful for debuging. 
	 * @param list
	 * @return converted to plain string
	 */
	public static String dump(List <Object> list){
		StringBuffer buffer=new StringBuffer();
		if(list==null)
			return "[null]";
		for (int i=0;i<list.size();i++){
			Object o=list.get(i);
			if(o!=null){
				buffer.append("["+i+"]="+o.toString()+"," );
			}else{
				buffer.append("["+i+"]=[null],");
			}
		}
		return buffer.toString();	
	}
	/**
	 * save key values in a hash map to a preference that is persisted in 
	 * a data file.  Will never save a preference that has null values.
	 * @param act
	 * @param values
	 */	
	public static void savePref(Activity act, Map <String,String> values){
		if(act==null || values==null){
			Log.e(TAG,"can not save null preference");
			return;	
		}
		Set <String> set = values.keySet();
		SharedPreferences settings = act.getSharedPreferences(TransitConst.PREFS_NAME, 0);
		SharedPreferences.Editor editor = settings.edit();
		Object[] keys=set.toArray ();
		int size=keys.length;
		for(int i=0;i<size;i++){
			if(keys[i]!=null && values.get(keys[i])!=null )
				editor.putString(keys[i].toString(), values.get(keys[i]).toString() );
		}

		editor.commit();

	}
	
	/**
	 * Will never save a preference that has null values.
	 * @see #savePref(Activity, Map)
	 * @param act
	 * @param key
	 * @param value
	 */
	public static void savePref(Activity act, String key ,String  value){
		if(act==null || key==null || value==null || value.length()<1){
			Log.e(TAG,"can not save null preference");
			return;
		}
		HashMap <String,String> map = new HashMap <String,String> ();
		
		map.put(key, value);
		TransitUtil.savePref(act, map);
	}

}
